import { CssVarsProvider, StyledEngineProvider, Textarea } from "@mui/joy";
import {
  Box,
  Chip,
  FormControl,
  Grid,
  Paper,
  TextField,
  Typography,
  useTheme,
} from "@mui/material";
import { DatePicker, DesktopDatePicker } from "@mui/x-date-pickers";
import { useMutation } from "@tanstack/react-query";
import { useSnackbar } from "notistack";
import React, { useMemo, useState } from "react";
import { useEffect } from "react";
import { useContext } from "react";
import { ThemeColorContext, UserProContext } from "../../../App";
import CommentArea from "../../../components/CommentArea";
import Dataform from "../../../components/Dataform";
import LoadingButton from "../../../components/LoadingButton";
import MyTextarea from "../../../components/MyTextArea";
import { GET_STUDENTWORK_URL } from "../../../constants/url";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import { TitleContext } from "../../../router";
import GetChipType from "./GetChipType";
import moment from "moment/moment";
import GetDetail from "./GetDetail";
import { renderCellExpand } from "../../../components/RenderCellExpand";
export default function StudentWork() {
  const titleContext = useContext(TitleContext);
  useEffect(() => {
    titleContext.setnowTitle(8);
  }, []);

  const columns = [
    {
      field: "id",
      headerName: "序号",
      flex: 1,
      editable: false,
    },
    {
      field: "position",
      renderCell: renderCellExpand,
      headerName: "职位",
      flex: 3,
    },
    {
      field: "beginTime",
      type: "dateTime",
      renderCell: renderCellExpand,
      headerName: "开始时间",
      flex: 3,
      // width: 150,
    },
    {
      type: "dateTime",
      field: "endTime",
      renderCell: renderCellExpand,
      headerName: "结束时间",
      // width: 150,
      flex: 3,
    },
    {
      // renderCell: renderCellExpand,
      field: "detail",
      headerName: "介绍",
      hideable: false,
      // flex: 3,
      width: 120,
      renderCell: GetDetail,
    },
    {
      field: "score",
      headerName: "发展分",
      flex: 2,
    },
    {
      renderCell: renderCellExpand,
      field: "department",
      headerName: "单位",
      flex: 3,
    },
    {
      field: "status",
      // renderCell: renderCellExpand,
      headerName: "状态",
      renderCell: GetChipType,
      // flex: 3,
      width: 150,
    },
  ];

  const {
    isLoading: updLoading,
    isSuccess: updSuccess,
    data: upddata,
    isError: updError,
    mutate: updMutate,
  } = useMutation(["updStudentwork"], mutateQueryFn);

  const {
    data,
    isLoading: getLoading,
    mutate: getMutate,
    isSuccess: getSuccess,
  } = useMutation(["getStudentwork"], mutateQueryFn);

  useEffect(() => {
    getMutate({ url: GET_STUDENTWORK_URL, method: "get", useToken: true });
  }, []);

  const userProContext = useContext(UserProContext);

  const [newItem, setNewItem] = useState({ score: 0 });
  const [rows, setRows] = useState([]);
  useEffect(() => {
    if (getSuccess) {
      setRows(
        data.data.data.map((val, key) =>
          val.status !== undefined
            ? {
                ...val,
                // status: val.status === 0 ? "申请中" : "通过",
                id: key + 1,
              }
            : {}
        )
      );
    }
  }, [data]);
  const handleUpd = () => {
    if (!newItem?.position) {
      enqueueSnackbar("职位不能为空", { variant: "warning" });
      return;
    }
    if (!newItem?.beginTime) {
      enqueueSnackbar("请选择开始时间", { variant: "warning" });
      return;
    }
    if (!newItem?.endTime) {
      enqueueSnackbar("请选择结束时间", { variant: "warning" });
      return;
    }
    if (!newItem?.department) {
      enqueueSnackbar("请选择单位", { variant: "warning" });
      return;
    }
    if (!newItem?.detail) {
      enqueueSnackbar("请填写详情", { variant: "warning" });
      return;
    }
    if (newItem.beginTime > newItem.endTime) {
      enqueueSnackbar("开始时间不能晚于结束时间", { variant: "warning" });
      return;
    }
    updMutate({
      url: GET_STUDENTWORK_URL,
      method: "put",
      data: {
        ...newItem,
        name: "name非空",
        beginTime: moment(newItem.beginTime.toString()).format("YYYY-MM-DD"),
        endTime: moment(newItem.endTime.toString()).format("YYYY-MM-DD"),
      },
      useToken: true,
    });
  };
  const [updbutSuccess, setUpdSuccess] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  useEffect(() => {
    if (updSuccess) {
      if (upddata.data.code != 0) {
        enqueueSnackbar(upddata.data.data, { variant: "error" });
      } else {
        setNewItem({ score: 0 });
        enqueueSnackbar("提交成功", { variant: "success" });
        getMutate({ url: GET_STUDENTWORK_URL, method: "get", useToken: true });
        setUpdSuccess(true);
        setTimeout(() => {
          setUpdSuccess(false);
        }, 1500);
      }
    }
  }, [updSuccess]);

  return (
    <div>
      <Grid container spacing={3}>
        <Grid item xs={4} md={12} lg={4} sm={12}>
          <Paper sx={{ padding: "20px 20px", marginBottom: 2 }}>
            <Typography sx={{ marginBottom: 3 }} variant="h5">
              学生工作经历申请
            </Typography>
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                // flexWrap: "wrap",
              }}
            >
              <Box flexGrow={1} sx={{ marginTop: 4 }}>
                <TextField
                  value={newItem.position}
                  onChange={(e) => {
                    setNewItem({ ...newItem, position: e.target.value });
                  }}
                  size="small"
                  label="职位*"
                ></TextField>
              </Box>
              <Box flexGrow={1} sx={{ marginTop: 4 }}>
                <TextField
                  value={newItem.score}
                  onChange={(e) => {
                    if (e.target.value >= 0)
                      setNewItem({ ...newItem, score: e.target.value });
                  }}
                  type="number"
                  size="small"
                  sx={{ width: 100 }}
                  label="发展分*"
                ></TextField>
              </Box>
              <Box flexGrow={1} sx={{ marginTop: 4 }}>
                <DesktopDatePicker
                  label="开始时间*"
                  disableFuture
                  value={newItem.beginTime ?? null}
                  onChange={(newValue) => {
                    setNewItem({ ...newItem, beginTime: newValue });
                  }}
                  renderInput={(params) => (
                    <TextField size="small" {...params} />
                  )}
                />
              </Box>
              <Box flexGrow={1} sx={{ marginTop: 4 }}>
                <DatePicker
                  label="结束时间*"
                  disableFuture
                  value={newItem.endTime ?? null}
                  onChange={(newValue) => {
                    setNewItem({ ...newItem, endTime: newValue });
                  }}
                  renderInput={(params) => (
                    <TextField size="small" {...params} />
                  )}
                />
              </Box>
              <Box sx={{ marginTop: 4 }} flexGrow={1}>
                <TextField
                  value={newItem.department}
                  onChange={(e) => {
                    setNewItem({ ...newItem, department: e.target.value });
                  }}
                  size="small"
                  label="单位*"
                ></TextField>
              </Box>
              <Box sx={{ marginTop: 3, width: "30%", minWidth: 300 }}>
                <MyTextarea
                  value={newItem.detail}
                  change={(e) => setNewItem({ ...newItem, detail: e })}
                  placeholder="详情"
                />
              </Box>
            </Box>
            <Box
              sx={{
                marginTop: 4,
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <LoadingButton
                titler={updbutSuccess ? "提交成功" : "提交申请"}
                clickr={handleUpd}
                isFetching={updLoading}
                isSuccess={updbutSuccess}
              />
            </Box>
          </Paper>
        </Grid>
        <Grid item xs={8} md={12} lg={8} sm={12}>
          <Dataform
            fileName={userProContext.userPro.name + " 学生工作经历"}
            rows={rows}
            loading={getLoading}
            columns={columns}
          />
        </Grid>
      </Grid>
      {/* )} */}
    </div>
  );
}
